window.addEventListener("load", init, false);

function init()
{
    v["constantes"] = new Object;
    v["constantes"].indiceAffichage = 2;
    v["constantes"].timer = setInterval("incrementeTimer()", 40);
    v["constantes"].timerCount = 0;
    v["constantes"].indiceAffichage = 2;
	v["constantes"].bNewMessage = false;
    $.getJSON("/rooms/reloadRooms", function(d){
        if(d.status){
            traitementRooms(d);
        }
    });
    document.addEventListener("keydown", keyDown, false);
    document.getElementById("message").addEventListener("keydown", function(e){
        if(e.keyCode == 13){ 
                ajoutTextChat(v["user"].pseudo, document.getElementById("message").value);
                document.getElementById("message").value = "";
        }
	}, false);
    document.getElementById("envoyer").addEventListener("click", function(){
            ajoutTextChat(v["user"].pseudo, document.getElementById("message").value);
            document.getElementById("message").value = "";
	}, false);
    
    for(var i=0; i < 11; i++){
        if(v["user"].perso == i){
            document.getElementById("perso"+i).checked = true;
        } else {
            document.getElementById("perso"+i).checked = false;
        }
    }
}

function incrementeTimer()
{
    v["constantes"].timerCount++;
    if(v["constantes"].timerCount%625 == 0){
        $.getJSON("/lobby/extendExpire", function(d){
            if(d.connected == false)
                {
                    window.location.reload();
                }
        });
    }
    if(v["constantes"].timerCount%105 == 0){
        $.getJSON("/rooms/reloadRooms", function(d){
            if(d.status){
                traitementRooms(d);
            }
        });
    }
    if(v["constantes"].bNewMessage){
		actualiserScroll();
	}
}

function traitementRooms(d)
{
	/*fonction permettant l'actualisation du tableau des joueurs connectés en le re-créant automatiquement*/
    var didYouFoundMe = false;
    $('.tr_single').remove();
    if(d.single.length > 0){
        for(var u in d.single){
            var U = d.single[u];
            var tr = document.createElement("tr");
            tr.setAttribute("class", "tr_single");
            var td = document.createElement("td");
            td.innerHTML = U.pseudo;
            tr.appendChild(td);
            td = document.createElement('td');
            td.innerHTML = "waiting";
            tr.appendChild(td);
            td = document.createElement('td');
            if(U.hash == v["user"].hash){
                td.innerHTML+= "(vous)";
                didYouFoundMe = true;
            } else {
                var a = document.createElement("a");
                a.setAttribute('href', "#");
                a.setAttribute('onclick', "invite('"+U.hash+"')");
                a.innerHTML = "inviter à jouer";
                td.appendChild(a);
            }
            tr.appendChild(td);
            $("#playinglist_table").find("tbody").append(tr);
        }
    }
    $('.tr_multi').remove();
    
    if(d.multi.length > 0){
        var pos = 0;var tr = null;var td = null;
        for(var u in d.multi){
            var U = d.multi[u];
            pos = U.position;
            var a;
            switch (pos)
            {
                case 1 :
                    tr = document.createElement("tr");
                    tr.setAttribute("class", "tr_multi");
                    td = document.createElement("td");
                    td.innerHTML = U.pseudo;
                    if(U.hash == v["user"].hash){
                        td.innerHTML+= " (vous)";
                        didYouFoundMe = true;
                    }
                    tr.appendChild(td);
                    var td2 = document.createElement("td");
                    td2.innerHTML = "ingame - room n°"+U.room;
                    tr.appendChild(td2);
                    td2 = document.createElement("td");
                    a = document.createElement("a");
                    if(U.hash == v["user"].hash)
                    {
                        a.setAttribute("href", "/game/index/"+U.room+"/");
                        a.innerHTML = ">> REPRENDRE VOTRE MATCH ! <<";
                    } else {
                        a.setAttribute("href", "/game/watch/"+U.room+"/");
                        a.innerHTML = "voir le match";
                    }
                    td2.appendChild(a);
                    tr.appendChild(td2);
                    break;
                case 2 :
                    td.innerHTML += "<br />"+U.pseudo;
                    if(U.hash == v["user"].hash){
                        td.innerHTML+= " (vous)";
                        a.setAttribute("href", "/game/index/"+U.room+"/");
                        a.innerHTML = ">> REPRENDRE VOTRE MATCH ! <<";
                        didYouFoundMe = true;
                    }
                    break;
            }
            $("#playinglist_table").find("tbody").append(tr);
        }
    }
    
    if(!didYouFoundMe){
        window.location.reload();
    }
}


function receivePushChatMessage(message)
{
    if(message.pseudo != v["user"].pseudo){
            ajoutTextChat(message.pseudo, message.texte);
    }
    v["constantes"].bNewMessage = true;
}

function receivePushUser(message)
{
    switch(message.type)
    {
        case "invite" :
            $( "#dialog:ui-dialog" ).dialog( "destroy" );
            $('#dialog-confirm-invite').attr('title', 'Invitation de '+message.pseudo);
            $('#dialog-confirm-invite-pseudo').html(message.pseudo);
            $("#dialog-confirm-invite").dialog({
                    resizable: true,
                    modal: true,
                    buttons: {
                            "Accepter l'invitation": function() {
                                    $.getJSON('/game/create/'+v["user"].hash+'/'+message.hash, function (data){
                                        if(data.erreur == 0){
                                            PUBNUB.publish({
                                                channel : "user-"+message.hash,
                                                message : {
                                                        "type" : "readyAfterInvite",
                                                        "pseudo" : v["user"].pseudo,
                                                        "hash" : v["user"].hash,
                                                        "room_id" : data.room_id
                                                    }
                                            });
                                            PUBNUB.publish({
                                                channel : "user-"+v["user"].hash,
                                                message : {
                                                        "type" : "readyAfterInvite",
                                                        "pseudo" : v["user"].pseudo,
                                                        "hash" : v["user"].hash,
                                                        "room_id" : data.room_id
                                                    }
                                            });
                                        } else {
                                            alert(data.message);
                                        }
                                    });
                                    $( this ).dialog( "close" );
                            },
                            "Décliner": function() {
                                    PUBNUB.publish({
                                        channel : "user-"+message.hash,
                                        message : {
                                                "type" : "declinedInvite",
                                                "pseudo" : v["user"].pseudo,
                                                "hash" : v["user"].hash
                                            }
                                    });
                                    $( this ).dialog( "close" );
                            }
                    }
            });
            break; 
        case "readyAfterInvite" :
            $( "#dialog:ui-dialog" ).dialog( "destroy" );
            $('#dialog-message-ready-pseudo').html(message.pseudo);
            $("#dialog-message-ready").dialog({
                    resizable: false,
                    modal: true,
                    buttons: {
                            Ok: function() {
                                    $( this ).dialog( "close" );
                            }
                    }
            });
            window.location.href = "/game/index/"+message.room_id;
            break;
            
        case "declinedInvite" :
            $( "#dialog:ui-dialog" ).dialog( "destroy" );
            $('#dialog-message-decline-pseudo').html(message.pseudo);
            $("#dialog-message-decline ").dialog({
                    resizable: false,
                    modal: true,
                    buttons: {
                            Ok: function() {
                                    $( this ).dialog( "close" );
                            }
                    }
            });
        break;
    }
}

function invite(hash)
{
    PUBNUB.publish({
        channel : "user-"+hash,
        message : {
                "type" : "invite",
                "hash" : v["user"].hash,
                "pseudo" : v["user"].pseudo
            }
    });
}

function changePerso(perso)
{
    $.get("/rooms/changePerso/"+perso);
}

function ajoutTextChat(pseudo, texte)
{
	if(texte != ""){
            if(pseudo == v["user"].pseudo){
                    PUBNUB.publish({
                        channel : "chat-rooms",
                        message : {
                                "texte" : texte,
                                "hash" : v["user"].hash,
                                "pseudo" : v["user"].pseudo
                            }
                    });
            }
			
           /* if(document.createElement("audio").canPlayType('audio/ogg')){
                document.getElementById("audio").setAttribute("src", "http://rbeuque74eu.blob.core.windows.net/files/sounds/pm_receive.ogg");
                document.getElementById("audio").play();
            } else if(document.createElement("audio").canPlayType('audio/mpeg')){
                document.getElementById("audio").src = "http://rbeuque74eu.blob.core.windows.net/files/sounds/pm_receive.mp3";
                document.getElementById("audio").play();
            } else if(document.createElement("audio").canPlayType('audio/x-wav')){
                document.getElementById("audio").src = "http://rbeuque74eu.blob.core.windows.net/files/sounds/pm_receive.wav";
                document.getElementById("audio").play();
            }*//*http://jplayer.org/HTML5.Audio.Support/*/
            
           
                document.getElementById("audio-src-ogg").setAttribute("src", "http://rbeuque74eu.blob.core.windows.net/files/sounds/pm_receive.ogg");
                document.getElementById("audio-src-mp3").setAttribute("src", "http://rbeuque74eu.blob.core.windows.net/files/sounds/pm_receive.mp3");
                document.getElementById("audio-src-wav").setAttribute("src", "http://rbeuque74eu.blob.core.windows.net/files/sounds/pm_receive.wav");
                document.getElementById("audio").load();
                document.getElementById("audio").play();
			
			if(document.getElementById("chat-view").innerHTML != ""){document.getElementById("chat-view").innerHTML += "<br/>";}
            document.getElementById("chat-view").innerHTML += "<strong>" +pseudo+ " :</strong> "+ texte;
	}
}



function actualiserScroll(){
	document.getElementById('chat-view').scrollTop = document.getElementById('chat-view').scrollTop + v["constantes"].indiceAffichage;
	v["constantes"].indiceAffichage++;
	if(document.getElementById('chat-view').scrollTop >= document.getElementById('chat-view').scrollHeight -200){
		v["constantes"].indiceAffichage =0;
        v["constantes"].bNewMessage = false;
	}	
}

function keyDown(e)
{
    if(e.keyCode == 13){ 
            if(!v["constantes"].focusOnMessage){document.getElementById("message").focus();}
            else{document.getElementById("message").blur();}
    }
}

function getXMLHttpRequest() {
	var xhr = null;
	
	if (window.XMLHttpRequest || window.ActiveXObject) {
		if (window.ActiveXObject) {
			try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
		} else {
			xhr = new XMLHttpRequest(); 
		}
	} else {
		alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
		return null;
	}
	
	return xhr;
}


function changePseudo()
{
    var url = document.getElementById("login").value;
    if(url != ""){
        var xhr = getXMLHttpRequest();

        xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
                       changeIndicatorPseudo(xhr.responseText);
                }
        };
        xhr.open("GET", "/lobby/checkAvailability/"+url, true);
        xhr.send(null);
    }
}